from django.shortcuts import render
from rest_framework.generics import GenericAPIView, CreateAPIView, ListAPIView, RetrieveAPIView
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import ReadOnlyModelViewSet
from areas.models import Area
from areas.serializers import AreaSerializer, AreaInfoSeriazlier
from rest_framework_extensions.cache.mixins import CacheResponseMixin

# # GET /areas/
# class AreaView(GenericAPIView):
#     serializer_class = AreaSerializer
#     queryset = Area.objects.filter(parent=None)
#
#     """获取所有省级地区"""
#     def get(self, request):
#         # areas = Area.objects.filter(parent=None)
#         areas = self.get_queryset()
#         # 序列化并返回
#         serializer = self.get_serializer(areas, many=True)
#
#         return Response(serializer.data)


# GET /areas/
# class AreaView(ListAPIView):
#     serializer_class = AreaSerializer
#     queryset = Area.objects.filter(parent=None)

    # """获取所有省级地区优化"""
    # def get(self, request):
    #     # areas = Area.objects.filter(parent=None)
    #     areas = self.get_queryset()
    #     # 序列化并返回
    #     serializer = self.get_serializer(areas, many=True)
    #
    #     return Response(serializer.data)


# class AreaDetailView(GenericAPIView):
#     """获取指定地区"""
#     serializer_class = AreaInfoSeriazlier
#     queryset = Area.objects.all()
#
#     def get(self, request, pk):
#         area = self.get_object()
#         serializer = self.get_serializer(area)
#
#         return Response(serializer.data)


# class AreaDetailView(RetrieveAPIView):
#     """获取指定地区优化代码"""
#     serializer_class = AreaInfoSeriazlier
#     queryset = Area.objects.all()

    # def get(self, request, pk):
    #     area = self.get_object()
    #     serializer = self.get_serializer(area)
    #
    #     return Response(serializer.data)


# 获取所有省级地区和获取指定地区的代码改写为视图集
# 继承cache类,使用缓存
class AreaViewSet(CacheResponseMixin, ReadOnlyModelViewSet):
    # 视图集改写视图
    pagination_class = None

    def get_queryset(self):
        if self.action == 'list':
            return Area.objects.filter(parent=None)
        else:
            return Area.objects.all()

    def get_serializer_class(self):
        if self.action == 'list':
            return AreaSerializer
        else:
            return AreaInfoSeriazlier
